<?php
            
use app\model\Record; 
use app\model\Comm; 
use app\model\Theme; 
use app\model\Poster; 
use app\model\Worker; 


/**
 * Author: cbw
 * Desc: 商家课程项目
 * Time: 2021/11/13 1:42 下午
 * Email: 17854288794@163.com
 */
require_once PATH_MODULE .'define.php';
class BeilaiModel extends PluginModel {

    public static function getUserFlagBySjId($themeid,$sjid,$page,$type=1)
    {
        $c_arr = [
            ['title'=>'全部','c_id'=>0,'total'=>0]
        ];
        //获取商家下的全部课程
        $sj_courses = self::getCourseList($themeid,$sjid,'',0,0,1,'',0);
        $c_total = 0;
        foreach ($sj_courses as $k => $v){
            $item_total = BeilaiModel::getPayOrderCourseTotal($themeid,$v['id']);
            $c_total+= $item_total;
            $tmp_arr = ['title'=>$v['name'],'c_id'=>$v['id'],'total'=>$item_total];
            array_push($c_arr,$tmp_arr);
        }
        $c_arr[0]['total'] = $c_total;
        if ($type==1){
            return $c_arr;
        }else{
            $page_index = max(1,intval($page));
            $page_size = 50;
            $page_start = ($page_index-1)*$page_size;
            $sj_courses_lists = self::getUserCourseFlag($themeid,$sjid,'',0,0,'','',0);
            $sj_courses_list = self::getUserCourseFlag($themeid,$sjid,'',$page_start,$page_size,'','',0);
            $max_page = ceil($sj_courses_lists/$page_size);
            foreach ($sj_courses_list as $k => $v){
                if ($v['status'] && $v['workerid']){
                    $check_worker = db_get(t_worker,['themeid'=>$themeid,'uid'=>$v['workerid']]);
                    $sj_courses_list[$k]['verify_name'] = $check_worker['username']?$check_worker['username']:'';
                    $sj_courses_list[$k]['updated_at'] = $check_worker['username']?$v['updated_at']:'';
                }
            }
            return  $sj_courses_list;
        }
    }

    public static function getUserCouponBySjId($themeid,$sjid,$page,$type=0)
    {
        $c_arr = [
            ['title'=>'全部','c_id'=>0,'total'=>0]
        ];
        $sj_coupons = self::getCouponList($themeid,$sjid,'',0,0);
        $c_total = 0;
        foreach ($sj_coupons as $k => $v){
            $item_total = self::getCouponTotal($themeid,$v['id']);
            $c_total+= $item_total;
            $tmp_arr = ['title'=>$v['name'],'c_id'=>$v['id'],'total'=>$item_total];
            array_push($c_arr,$tmp_arr);
        }
        $c_arr[0]['total'] = $c_total;
        if ($type==0){
            return $c_arr;
        }
        $page_index = max(1,intval($page));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $total = self::getUserCouponFlag($themeid,$sjid,'',0,0,'','',0,true);
        $list = self::getUserCouponFlag($themeid,$sjid,'',$page_start,$page_size,'','',0);
        $max_page = ceil($list/$page_size);
        return  ['total'=>$total,'max_page'=>$max_page,'list'=>$list];
    }

    public static function getCouponTotal($themeid,$id=0,$type='')
    {
        $condition = "";
        if ($type){
            $condition .= " and status='$type'";
        }
        $sql = "select count(*) as cnt from".tablename(t_shangjia_user_coupon).
            " where themeid='$themeid' and coupon_id='$id' ".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取贝莱基础首页数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 10:10 上午
     * @return array
     */
    public static function getBeiLaiConfig()
    {
        global $_P, $_G, $_C,$_S;
        $_S = $system = self::getSystem();
        $uid = $_G['member']['uid'];
        if (!$uid){
            exit();
        }
        $themeid = $_P['themeid'];
        $fromuid = $_P['fromuid'];
        $workerid = $_P['workerid'];
        $fans = db_get(t_fans,['uid'=>$uid,'themeid'=>$themeid]);
        $theme = Theme::getThemeById($themeid);
        $_C = $config =    Theme::getConfig($themeid);
        $shangjia_list = self::getShangjiaList();
        //机构视频
        $sj_list = [];
        //机构详情
        $sj_detail_list = [];
        foreach ($shangjia_list as $key =>$val){
            $sj_list_data = ['name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
                'video'=>$val['videoyouku'],
                'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo']
            ];
            array_push($sj_list,$sj_list_data);
            //获取机构课程
            $sj_course_list = self::getCourseList($themeid,$val['id'],'',0,0);
            $sj_course_total = self::getCourseTotal($themeid,$val['id']);
            if ($sj_course_total>0){
                array_push($sj_detail_list,
                    [
                        'name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
                        'video'=>$val['videoyouku'],
                        'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo'],
                        'content'=>$val['content'],
                        'address'=>json_decode($val['address'],true),
                        'courses'=>$sj_course_list,
                        'address_total' => count(json_decode($val['address'],true)),
                        'course_total'=>$sj_course_total,
                        'order_total'=>$val['order_total'],
                        'kefu'=>['avatar'=>$val['logo'],'mobile'=>$val['mobile'],'name'=>$val['name'].'客服']
                    ]);
            }

        }

       // $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        //判断团长身份
        $themyrecord = Record::getLastGroupByUid($uid,$themeid);
        //奖励详情
        $sj_setting = [];
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $item['tuan'] = json_decode($item['tuan'],true);
        $item['order'] = json_decode($item['order'],true);

        $other_config = json_decode($item['other_config'],true);
        $school_other_name = $other_config['school_other_name'];
        $course_other_name = $other_config['course_other_name'];
        $gift_other_name = $other_config['gift_other_name'];
        $open_position = $other_config['open_position'];
        $open_shangjia_video = $other_config['open_shangjia_video'];
        $bl_buy_history = $other_config['bl_buy_history'];

//        if (strpos("a".$config['province'].'省', $_G['address']['province']) == false || strpos("a".$_G['address']['province'],'广东' ) !== false){
//            $bl_buy_history =2;
//        }
        //报名数据+头像配置处理
        //只显示头像昵称
        if ($config['iswttouxiang']==1){
            $bl_buy_history =2;
        }
        //本地用户显示
        if (empty($_G['address']['province']) || $config['iswttouxiang']==9 && strpos("a".$config['province'].'省', $_G['address']['province']) == false){
            $bl_buy_history =2;
        }
        //都不显示
        if ($config['iswttouxiang']==10){
            $bl_buy_history =2;
        }
        //广东地区任何条件都不显示
        if (strpos("a".$_G['address']['province'],'广东' ) !== false){
            $bl_buy_history =2;
        }

        $show_course_flag = $other_config['show_course_flag'];//显示课程选择数 以及统计数据
//        if ($system['softstyle']==108){
//            //异业：贝莱亲子
//            $open_shangjia_video = true;
//        }

        $poster_show = $item['poster_show'];
        $item_order_count = count($item['order']);
        $temp_arr = [];
        $temp_total_arr = [];
        if ($item['tuan'] && is_array($item['tuan'])){
            foreach ($item['tuan'] as $key => $val)
            {
                if ($val['key']=='主图'){
                    $temp_arr['img'] = $val['val'];
                }
                if ($val['key']=='提供商家'){
                    $temp_arr['shangjia'] = $val['val'];
                }
                if ($val['key']=='奖品'){
                    $temp_arr['title'] = $val['val'];
                }
                if ($val['key']=='价值'){
                    $temp_arr['price'] = $val['val'];
                }
                if ($val['key']=='奖励描述'){
                    $temp_arr['detail'] = $val['val'];
                }
                $temp_arr['from'] = '成团解锁(团长)';
            }
            array_push($temp_total_arr,$temp_arr);
        }

        if ($item['order'] && is_array($item['order'])){
            foreach ($item['order'] as $key => $val){
                $temp_array = [];
                $temp_array['img'] = $val['img'];
                $temp_array['shangjia'] = $val['shangjia_name'];
                $temp_array['title'] = $val['name'];
                $temp_array['price'] = $val['price'];
                $temp_array['from'] = '累计邀请'.$val['invite'].'人解锁';
                $temp_array['detail'] =   db_getcolumn(t_shangjia_gift, array('id' => $val['gift_id']), 'detail');
                array_push($temp_total_arr,$temp_array);
            }
        }
        //赠品list
        $free = self::getGiftList($themeid,0,'',0,0,0,1);
        if ($free && is_array($free)){
            foreach ($free as $key => $val){
                $temp_arr = [];
                $temp_arr['img'] = $val['top_img'];
                $temp_arr['shangjia'] = $val['shangjia_name'];
                $temp_arr['title'] = $val['name'];
                $temp_arr['price'] = $val['price'];
                $temp_arr['from'] = '购买解锁';
                $temp_arr['detail'] = $val['detail'];
                array_unshift($temp_total_arr,$temp_arr);
            }
        }
        //课程列表
        $new_course_list = [];
        $course_list = self::getCourseList($themeid,0,'',0,0);
        foreach ($course_list as $key => $val)
        {
            $temp_arr = [];
            $temp_arr['id'] = $val['id'];
            $temp_arr['name'] = $val['name'];
            $temp_arr['price'] = $val['price'];
            $temp_arr['sales'] = $val['selected_num'];
            $temp_arr['shangjia'] = $val['shangjia_name'];
            $temp_arr['shangjia_id'] = $val['shangjia_id'];
            $temp_arr['address'] = json_decode($val['address'],true);
            array_push($new_course_list,$temp_arr);
        }
        //判断员工
        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
        //最新订单

        $order_list = self::getOrderList($themeid);
        if ($_S['softstyle']==108 && $_S['beilai_style']==1){
            $order_list = self::formatFrontOrderList($themeid,$config);
        }


        //判断优惠券  修改为获取worker_id  找到商家  找独享  找通用  判断时间
        $coupon_item = self::userGetCoupon($themeid,$uid,$workerid);

        //判断海报
        $poster = Poster::getByThemeIdnew($themeid);
        if(!empty($poster['bg'])){
            $config['isposter']=1;
            if ($fans['status']==2 && $system['s']['istubiao']==1) {
                $config['isposter']=0;
            }
            $pm = ['themeid'=>$themeid,'openid'=>$fans['openid']];
            $myposter = db_find("SELECT * FROM ".tablename(t_fans)."
             WHERE themeid = :themeid and openid = :openid",$pm);
            if (empty($myposter['poster'])){
                $waittips = empty($poster['waittips'])?'正在生成海报':$poster['waittips'];
            }else{
                $waittips='';
            }
            //获取海报的url地址
            $posterurl = "/" . createMobileUrl("poster",array("themeid"=>$themeid,"op"=>"action","fromuid"=>$_P['fromuid'],"fopenid"=>$_P['fopenid'],"recordid"=>intval($themyrecord['id'])));

        }else{
            $waittips='海报未开启';
        }

        //伪小程序
        if ($system['pn_wxapp']==3){
            $poster_show==2;
        }
        //        能否分享
        $canshare = 1;
        if ($system['softstyle']==108){
            if (!$themyrecord && !$myworker && $poster_show==2){
                $posterurl = '';
                $waittips = '成功购买课程后，才能生成海报';
                $canshare=0;
            }
        }
//        if ($_S['pn_wxapp']==0 || $_S['pn_wxapp']==1){
        if ($_S['pn_wxapp']==1){
            $posterurl = '';
            $waittips = '未开启分享功能';
            $canshare=0;
        }
        $poster_info = ['tips'=>$waittips,'img_url'=>$posterurl];

        //客服
        $kefu = ['qr_code'=>$config['kfewm'],'mobile'=>$theme['mobile']];
        //底部图片
        $setting = BeilaiModel::getRewardByWhere(['themeid'=>$themeid]);
        //倒计时
        $can_countdown = false;
        $countdown_time = 0;
        $now_time = time();
        if (($theme['begintime']<$now_time) && ($now_time<$theme['endtime']) && $theme['status']=='1') {
            $can_countdown = true;
            $countdown_time = $theme['endtime']-$now_time;
        }
        //判断福利领取记录
        $flag_list = BeilaiModel::getUserGift($themeid,0,'',0,20);
        $format_user_flag_list = [];
        foreach ($flag_list as $kk => $vv){
            $temp_arr = [
                'avatar'=>$vv['avatar']?$vv['avatar']:'https://css2020.yixuan.net/2020css/yx2020/images/question.png',
                'nickanme'=>$vv['username']?$vv['username']:$vv['nickname'],
                'txt'=>'解锁价值'.$vv['price'].$vv['name'],
                'status_txt'=>'开团成功',
                'time'=>date("Y-m-d",strtotime($vv['created_at']))
            ];
            array_push($format_user_flag_list,$temp_arr);
        }

        $company_show_name = '机构';
        if (MODULE_NAME == 'sd33855' || MODULE_NAME == 'yx18900') {
            $company_show_name = '分类';
        }

//        self::beilaiCheck($themeid);
        return [
            'shangjia_list'=>$shangjia_list,
            'sj_list'=>$sj_list,
            'sj_detail_list'=>$sj_detail_list,
            'item_order_count'=>$item_order_count,
            'temp_total_arr'=>$temp_total_arr,
            'new_course_list'=>$new_course_list,
            'myworker'=>$myworker,
            'coupon_item'=>$coupon_item,
            'poster_info'=>$poster_info,
            'order_list'=>$order_list,
            'kefu'=>$kefu,
            'setting'=>$setting,
            'can_countdown'=>$can_countdown,
            'countdown_time'=>$countdown_time,
            'user_flag_list'=>$format_user_flag_list,//福利领取记录
            'canshare'=>$canshare,
            'school_other_name'=>$school_other_name,
            'course_other_name'=>$course_other_name,
            'gift_other_name'=>$gift_other_name,
            'open_position'=>$open_position,
            'open_shangjia_video'=>$open_shangjia_video,
            'bl_buy_history'=>$bl_buy_history,
            'show_course_flag'=>$show_course_flag,
            'company_show_name'=>$company_show_name,
        ];
    }

    /**
     * Desc:修正商家报名 以及课程选择量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/13 16:24
     * @param $themeid
     */
    public static function beilaiCheck($themeid)
    {
        $shangjia_list = self::getShangjiaList();
        //更新商家订单
        foreach ($shangjia_list as $k => $v){
            $sql = ' select a.* from '.tablename(t_shangjia_address_user_course)." as a ".
                " left join ".tablename(t_record)." as b on a.order_id = b.id ".
                " where a.themeid=$themeid and a.shangjiaid={$v['id']} and b.status=1 group by a.order_id";
            $order_flag_list = db_select($sql);
            if ($order_flag_list){
                foreach ($order_flag_list as $key => $val){
                    $shangjia_item = db_get(t_shangjia,['id'=>$val['shangjiaid']]);
                    $new_order_total = count($order_flag_list);
                    $update_shangjia = db_update(t_shangjia,['order_total'=>$new_order_total],['id'=>$val['shangjiaid']]);
                }
            }
        }
        //更新课程选择
        $course_sql = "SELECT * FROM ".tablename(t_shangjia_course)." where themeid=$themeid ";
        $course_all = db_select($course_sql);
        foreach ($course_all as $k => $v){
            $sql1 = ' select a.* from '.tablename(t_shangjia_address_user_course)." as a ".
                " left join ".tablename(t_record)." as b on a.order_id=b.id ".
                " where a.themeid=$themeid and a.course_id={$v['id']} and b.status=1 ";
            $order_flag_list1 = db_select($sql1);
            if ($order_flag_list1){
                $course_item = self::getCourseItemById($themeid,$v['id']);
                $where = ['themeid'=>$themeid,'id'=>$v['id']];
                $data = ['selected_num'=>count($order_flag_list1)];
                $update = self::editCourseItem($where,$data);
            }
        }
    }

    public static function getPayOrderCourseTotal($themeid,$course)
    {
        $sql = " select count(*) as cnt from ".tablename(t_shangjia_address_user_course)." as a ".
        " left join ".tablename(t_record)." as b on a.order_id = b.id ".
        " where a.themeid=$themeid and a.course_id='$course' and b.status=1 ";
        return db_find($sql)['cnt'];
    }

    public static function checkThemeStatus($theme)
    {
        $now_time = time();
        if ($theme['begintime']>$now_time) {
            return 0;
        }
        if ($now_time>$theme['endtime']) {
            return 0;
        }
        if ($theme['status']=='2'){
            return 0;
        }
        return 1;
    }

    /**
     * Desc:检查活动是否停止
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 3:47 下午
     * @param $theme
     * @return bool
     */
    public static function checkThemeEnd($theme)
    {
        $is_end = false;
        $now_time = time();
        if ($now_time>$theme['endtime']) {
            $is_end = true;
        }
        if ($theme['status']=='2'){
            $is_end = true;
        }
        return $is_end;
    }

    /**
     * Desc:判断用户是否存在礼品获得记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 6:48 下午
     * @param $themeid
     * @param $gift_id
     * @param $uid
     * @return mixed
     */
    public static function checkUserHasGift($themeid,$gift_id,$uid)
    {
        return db_get(t_shangjia_user_gift,['themeid'=>$themeid,'uid'=>$uid,'gift_id'=>$gift_id,'status'=>2]);
    }

    public static function getUserOrderGiftTotalByWhere($themeid,$status,$order_id,$is_verify)
    {
        $condition = "";
        if ($is_verify){
            $condition .= ' and workerid >0';
        }
        $sql = " select count(*) as cnt from".tablename(t_shangjia_user_gift)." where themeid='$themeid' and status='$status' and order_id='$order_id'".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:插入用户赠品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/5 8:21 下午
     * @param $data
     * @return mixed
     */
    public static function insertUserGift($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_user_gift,$data);
    }

    /**
     * Desc:删除同一订单号下的礼品选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/6 9:14 下午
     * @param $where
     * @return mixed
     */
    public static function delUserGiftByWhere($where)
    {
        return db_delete(t_shangjia_user_gift,$where);
    }

    /**
     * Desc:更新用户领取的礼品数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 2:15 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateUserGift($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_user_gift,$data,$where);
    }


    /**
     * Desc:检查活动是否开始
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 3:49 下午
     * @param $theme
     * @return int|string
     */
    public static function checkThemeStart($theme)
    {
        $is_start = '';
        $now_time = time();
        if ($theme['begintime']>$now_time) {
            $is_start = $theme['begintime']-$now_time;
        }
        return $is_start;
    }

    /**
     * Desc:获取用户获取的赠品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 9:21 下午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getFreeFlag($uid,$themeid)
    {
        return db_getall(t_shangjia_user_gift,['uid'=>$uid,'themeid'=>$themeid,'status'=>1,'can_use'=>1]);
    }

    /**
     * Desc:获取好友下单数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 7:18 下午
     * @param $themeid
     * @param $from_uid
     * @return mixed
     */
    public static function getFriendOrderTotal($themeid,$from_uid,$is_tuan=false,$pid=0)
    {
        
        if ($is_tuan){
            if (empty($pid)){
                return 0;
            }
            $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_record)." where themeid='$themeid' and fromuid='$from_uid' and (status=1 or status=3) and pid!='$pid'";
        }else{
            $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_record)." where themeid='$themeid' and fromuid='$from_uid' and uid!='$from_uid' and (status=1 or status=3)";
        }

        return db_find($sql)['cnt'];
    }

    /**
     * Desc:查找团长订单
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/7 11:50 上午
     * @param $themeid
     * @param $pid
     * @return mixed
     */
    public static function getTunaGroupItem($themeid,$pid)
    {
        $sql = " select * from ".tablename(t_record)." where themeid=$themeid and pid=$pid and status>0 and isfinish=1";
        return db_find($sql);
    }



    /**
     * Desc:支付成功后的
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/4 7:20 下午
     */
    public static function payRollback($themeid,$uid,$order_id)
    {
        $config =  Theme::getConfig($themeid);
        /**
         * 红包发放
         */
//        self::redPackageOut($themeid,$uid);
        /**
         * 判断成团礼 邀请礼
         */
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);

        $order_item = Record::getLastGroupByUid($uid,$themeid);

        //判断模式
        $other_config = json_decode($setting['other_config'],true);
        $gift_unlock_min_num = $other_config['gift_unlock_min_num'];
        $gift_unlock_max_num = $other_config['gift_unlock_max_num'];
        $lock_gift_mode = $other_config['lock_gift_mode'];
        $lock_gift_type = $other_config['lock_gift_type'];
        //下单解锁
        if ($lock_gift_type==1){
            //---------------------团长礼处理逻辑
            $tuan_order_item = db_get(t_record,['themeid'=>$themeid,'id'=>$order_item['pid'],'type'=>0,'status'=>1]);
            if ($tuan_order_item){
                //判断团长身份
                $themyrecord = Record::getLastGroupByUid($tuan_order_item['uid'],$themeid);
            }else{
                $themyrecord = [];
            }
            //判断当前订单的团长
            if ($themyrecord){
                $tuan_group_item = self::getTunaGroupItem($themeid,$themyrecord['pid']);
                //如果没有成团
                if (!$tuan_group_item){
                    //查找推荐人是否是团长
                    $from_user_themyrecord = Record::getLastGroupByUid($themyrecord['fromuid'],$themeid);
                    if (!$from_user_themyrecord){
                        $tuan_group_item =[];
                    }else{
                        $tuan_group_item = self::getTunaGroupItem($themeid,$from_user_themyrecord['pid']);
                    }
                }
            }else{
                $tuan_group_item =[];
            }
            //判断团长
            if ($tuan_group_item && $tuan_group_item['type']==0 && $tuan_group_item['status']>0 && $tuan_group_item['isfinish']==1){
                $tuan_gift_info = json_decode($setting['tuan'],true);
                if (!empty($tuan_gift_info)){//设置了成团奖励
                    foreach ($tuan_gift_info as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id = $val['val'];
                        }
                    }
                    $tuan_gift = self::getGiftItemById($themeid,$tuan_gift_id);
                    if ($tuan_gift_id && $tuan_gift){//设置了成团奖励 并且礼品存在
                        //插入团长礼品
                        //检查用户是否存在记录
                        $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$tuan_group_item['uid']);

                        if (!$check_tuan_gift){
                            $insert_data = ['order_id'=>$tuan_group_item['id'],'uid'=>$tuan_group_item['uid'],'shangjiaid'=>$tuan_gift['shangjiaid'],
                                'gift_id'=>$tuan_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                            ];
                            $res = self::insertUserGift($insert_data);
                        }
                    }
                }

            }
            //---------------------团长礼处理逻辑


            //---------------------下单礼
            $free_gift_item = db_get(t_shangjia_user_gift,['themeid'=>$themeid,'uid'=>$uid,'can_use'=>0]);
            if ($free_gift_item){
                //更新礼品订单号
                $where = ['themeid'=>$themeid,'uid'=>$uid,'can_use'=>0];
                $update_data = ['order_id'=>$order_id,'can_use'=>1];
                $res = self::updateUserGift($where,$update_data);
            }
            //---------------------下单礼

            //---------------------邀请礼
            //不限制  仅判判断邀请人是否付款
            $fromuid = $order_item['fromuid'];
            //判断上级 邀请人数
            $from_order_item = Record::getLastGroupByUid($fromuid,$themeid);
            //当前uid 不等于 fromuid
            if ($from_order_item && $from_order_item['status']==1 && $fromuid !=$uid){
                //推荐人必须下单
                $friend_order_total = (int)self::getFriendOrderTotal($themeid,$fromuid);
                if ($friend_order_total){
                    $order_gift_info = json_decode($setting['order'],true);
                    foreach ($order_gift_info as $key => $val){
                        if ($friend_order_total>=$val['invite']){
                            $order_gift_id = $val['gift_id'];
                            $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                            $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$fromuid);
                            if (!$check_order_gift){
                                $insert_data = ['order_id'=>$from_order_item['id'],'uid'=>$from_order_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                    'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                ];
                                $res = self::insertUserGift($insert_data);
                            }
                        }
                    }
                }
            }
            //---------------------邀请礼

        }else{
            $tuan_order_item = db_get(t_record,['themeid'=>$themeid,'id'=>$order_item['pid'],'type'=>0,'status'=>1]);

            if ($tuan_order_item){
                //判断团长身份
                $themyrecord = Record::getLastGroupByUid($tuan_order_item['uid'],$themeid);
            }else{
                $themyrecord = [];
            }

            //判断当前订单的团长
            if ($themyrecord){
                $tuan_group_item = self::getTunaGroupItem($themeid,$themyrecord['pid']);
                //如果没有成团
                if (!$tuan_group_item){
                    //查找推荐人是否是团长
                    $from_user_themyrecord = Record::getLastGroupByUid($themyrecord['fromuid'],$themeid);
                    if (!$from_user_themyrecord){
                        $tuan_group_item =[];
                    }else{
                        $tuan_group_item = self::getTunaGroupItem($themeid,$from_user_themyrecord['pid']);
                    }
                }
            }else{
                $tuan_group_item =[];
            }


            if ($tuan_group_item && $tuan_group_item['type']==0 && $tuan_group_item['status']>0 && $tuan_group_item['isfinish']==1){
                $tuan_gift_info = json_decode($setting['tuan'],true);
                if (!empty($tuan_gift_info)){//成团奖励存在
                    foreach ($tuan_gift_info as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id = $val['val'];
                        }
                    }
                    $tuan_gift = self::getGiftItemById($themeid,$tuan_gift_id);
                    if ($tuan_gift_id && $tuan_gift){//
                        //插入团长礼品
                        //检查用户是否存在记录
                        $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$tuan_group_item['uid']);

                        if (!$check_tuan_gift){
                            $insert_data = ['order_id'=>$tuan_group_item['id'],'uid'=>$tuan_group_item['uid'],'shangjiaid'=>$tuan_gift['shangjiaid'],
                                'gift_id'=>$tuan_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                            ];
                            $res = self::insertUserGift($insert_data);
                        }
                    }
                }

            }

            //判断邀请人数
            if ($tuan_group_item && $tuan_group_item['type']==0 && $tuan_group_item['status']>0 && $tuan_group_item['isfinish']==1){
                //判断团长身份
                $friend_order_total = (int)self::getFriendOrderTotal($themeid,$tuan_group_item['uid'],true,$tuan_group_item['pid']);

                if ($friend_order_total){
                    $tuan_gift_info = json_decode($setting['tuan'],true);
                    foreach ($tuan_gift_info as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id = $val['val'];
                        }
                    }
                    //检查用户是否存在记录
                    $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$tuan_group_item['uid']);

                    if ($check_tuan_gift){
                        //邀请人数的计算  不在同一个团内 计数
//                    $friend_order_total = max(0,($friend_order_total-$config['maxcountall']));

                        //判断是否存在团长礼
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$tuan_group_item['uid']);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$tuan_group_item['id'],'uid'=>$tuan_group_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }


            //更新用户的礼品
            //查询用户已获取的礼品
            $free_gift_item = db_get(t_shangjia_user_gift,['themeid'=>$themeid,'uid'=>$uid,'can_use'=>0]);
            if ($free_gift_item){
                //更新礼品订单号
                $where = ['themeid'=>$themeid,'uid'=>$uid,'can_use'=>0];
                $update_data = ['order_id'=>$order_id,'can_use'=>1];
                $res = self::updateUserGift($where,$update_data);
            }

            //判断团长内团员的邀请
            if ($order_item){

                $fromuid = $order_item['fromuid'];
                //判断邀请人是否是团员
                $from_order_item = Record::getLastGroupByUid($fromuid,$themeid);

                if ($from_order_item && $from_order_item['type']==1 && $order_item['pid']!=$from_order_item['pid'] && $from_order_item['isfinish']==1){

                    $friend_order_total = (int)self::getFriendOrderTotal($themeid,$from_order_item['uid']);

                    if ($friend_order_total){
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$from_order_item['uid']);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$from_order_item['id'],'uid'=>$from_order_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }
        }


        //更新用户的选择课程
        $course_where = ['themeid'=>$themeid,'uid'=>$uid];
        $course_data = ['order_id'=>$order_id];
        $res = self::updateUserCourseAddress($course_where,$course_data);
        //更新用户的优惠券
        $user_coupon_item = db_get(t_shangjia_user_coupon,['uid'=>$uid,'themeid'=>$themeid,'status'=>1]);
        if ($user_coupon_item){
            $coupon_item = db_get(t_shangjia_coupon,['id'=>$user_coupon_item['coupon_id']]);
            //判断优惠券是否可用
            $now = date("Y-m-d H:i:s",time());
            if ($coupon_item && ($coupon_item['use_start_time']<=$now) && ($now<=$coupon_item['use_end_time'])){
                //判断当前优惠券是否可使用
                //更新商家优惠券
                $new_use_num = $coupon_item['use_num']+1;
                $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                $update_data = ['use_num'=>$new_use_num];
                $result1 = self::editCouponItem($where,$update_data);
                //更新用户优惠券状态
                $user_coupon_where= ['themeid'=>$themeid,'uid'=>$uid,'id'=>$user_coupon_item['id']];
                $user_coupon_data= ['status'=>2,'order_id'=>$order_id];
                $res1 = self::updateUserCoupon($user_coupon_where,$user_coupon_data);
            }
        }

        //更新课程选择数 商家选择数
        //获取当前用户订单下的课程 以及选择商家
        $user_all_list = self::getUserAllCourseAddress(['order_id'=>$order_id,'themeid'=>$themeid]);
        foreach ($user_all_list as $key =>$val){
            $course_item = self::getCourseItemById($themeid,$val['course_id']);
            $where = ['themeid'=>$themeid,'id'=>$val['course_id']];
            $data = ['selected_num'=>$course_item['selected_num']+1];
            $update = self::editCourseItem($where,$data);
            //更新商家报名
            $shangjia_item = db_get(t_shangjia,['id'=>$val['shangjiaid']]);
            $new_order_total = $shangjia_item['order_total']+1;
            $update_shangjia = db_update(t_shangjia,['order_total'=>$new_order_total],['id'=>$val['shangjiaid']]);
        }
        self::beilaiCheck($themeid);
    }

    /**
     * Desc:获取用户所有的课程地址选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/13 11:56
     * @param $where
     * @return mixed
     */
    public static function getUserAllCourseAddress($where)
    {
        return db_getall(t_shangjia_address_user_course,$where);
    }

    public static function randomFloat($min,$max)
    {
        $new_min = $min*100;
        $new_max = $max*100;
        $num = mt_rand($new_min,$new_max)/100;
        return $num;
    }

    /**
     * Desc:红包发放
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 9:23 上午
     */
    public static function redPackageOut($themeid,$uid)
    {
        return;
        $fans = db_get(t_fans,['themeid'=>$themeid,'uid'=>$uid]);
        //获取订单
        $themyrecord = Record::getLastGroupByUid($uid,$themeid);
        //判断上级是否是员工
        $myworker = Worker::getThemeWorkerByOpenidNew($themyrecord['fopenid'],$themeid);
        if ($myworker){
            $setting = self::getRewardByWhere(['themeid'=>$themeid]);
            if ($setting && $setting['min_out_price'] && $setting['max_out_price'])
            {
                //获取随机金额
                $randomfee = self::randomFloat($setting['group_min_out_price'],$setting['group_max_out_price']);
                //使员工发团长提成
                $ordersn = getMillisecond();
                $data = array(
                    'uniacid' => $themyrecord['uniacid'],
                    'themeid' => $themyrecord['themeid'],
                    'recordid' => $themyrecord['id'],
                    'ordersn' => $ordersn,
                    'type' => 6,//员工提成类型
                    'openid' => $myworker['openid'],
                    'uid' => $myworker['uid'],
                    'addtime' => TIMESTAMP,
                    'fee' => $randomfee,
                    'fopenid' => $themyrecord['openid'],
                    'fromuid' => $themyrecord['uid'],
                    'status' => 0,
                );

                $res = Comm::add($data);
            }
        }else{
            $parent_item = db_get(t_record,['themeid'=>$themeid,'uid'=>$themyrecord['fromuid']]);

            if ($parent_item){
                //当前用户与上级pid是否一致
                if ($parent_item['pid']==$themyrecord['pid']){
                    //查找此团的团长
                    $group_item_order = db_get(t_record,['themeid'=>$themeid,'id'=>$parent_item['pid'],'type'=>0]);

                    if ($group_item_order){
                        //判断团长的推荐人是否是员工
                        $isworker = Worker::getThemeWorkerByOpenidNew($group_item_order['fopenid'],$themeid);

                        if ($isworker){
                            $setting = self::getRewardByWhere(['themeid'=>$themeid]);
                            if ($setting && $setting['min_out_price'] && $setting['max_out_price']){
                                //团员提成
                                $randomfee = self::randomFloat($setting['min_out_price'],$setting['max_out_price']);
                                $ordersn = getMillisecond();
                                $data = array(
                                    'uniacid' => $themyrecord['uniacid'],
                                    'themeid' => $themyrecord['themeid'],
                                    'recordid' => $themyrecord['id'],
                                    'ordersn' => $ordersn,
                                    'type' => 6,//员工提成类型
                                    'openid' => $isworker['openid'],
                                    'uid' => $isworker['uid'],
                                    'addtime' => TIMESTAMP,
                                    'fee' => $randomfee,
                                    'fopenid' => $themyrecord['openid'],
                                    'fromuid' => $themyrecord['uid'],
                                    'status' => 0,
                                );

                                $res = Comm::add($data);
                            }
                        }
                    }

                }
            }
        }
    }
    //预订单生成
    public static function apiInsertUserInfo($themeid,$recordid,$coupon_id)
    {

        //        $params = [
//            'gift_ids'=>"1,2",
//            'course_address'=>[['shangjia_id'=>1,'courseid'=>1,'address'=>'dizhi']]
//        ];
        global $_P, $_G;
        $course_address = $_P['course_address'];
        $gift_ids = explode(",",$_P['gift_ids']);
        foreach ($course_address as $key => $val)
        {
            $course_ids .= $val['courseid'].',';
        }
        $order_item = db_get(t_record,['id'=>$recordid,'themeid'=>$themeid]);
        $uid = $order_item['uid'];

        //判断用户是否存在同一订单号的礼品选择记录
        $delete_gift = self::delUserGiftByWhere(['themeid'=>$themeid,'uid'=>$uid]);

        //插入礼品、选择课程
        if ($gift_ids && is_array($gift_ids)){
            foreach ($gift_ids as $key => $val)
            {
                $item = self::getGiftItemById($themeid,$val);
                $data = ['order_id'=>$recordid,'uid'=>$uid,'shangjiaid'=>$item['shangjiaid'],
                    'gift_id'=>$val,'status'=>1,'themeid'=>$themeid];
                if ($val && $item && $item['shangjiaid']){
                    $res = self::insertUserGift($data);
                }
            }
        }
        //删除用户存在同一订单号的课程选择记录
        $delete_course = self::deleteUserCourseAddressByWhere(['themeid'=>$themeid,'uid'=>$uid]);
        //插入选择课程以及校区
        foreach ($course_address as $key => $val)
        {
            $data = [
                'order_id'=>$recordid,
                'uid'=>$uid,
                'shangjiaid'=>$val['shangjia_id'],
                'course_id'=>$val['courseid'],
                'address'=>$val['address'],
                'themeid'=>$themeid
            ];
            $res = self::insertUserCourseAddress($data);
            //以下代码移动到支付回调中
//            //更新课程
//            $course_item = self::getCourseItemById($themeid,$val['courseid']);
//            $where = ['themeid'=>$themeid,'id'=>$val['courseid']];
//            $data = ['selected_num'=>$course_item['selected_num']+1];
//            $update = self::editCourseItem($where,$data);
//            //更新商家报名
//            $shangjia_item = db_get(t_shangjia,['id'=>$val['shangjia_id']]);
//            $new_order_total = $shangjia_item['order_total']+1;
//            $update_shangjia = db_update(t_shangjia,['order_total'=>$new_order_total],['id'=>$val['shangjia_id']]);
        }
    }

    /**
     * Desc:插入用户优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/5 8:21 下午
     * @param $data
     * @return mixed
     */
    public static function insertUserCoupon($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_user_coupon,$data);
    }

    /**
     * Desc:更新用户优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 3:29 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateUserCoupon($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_user_coupon,$data,$where);
    }

    /**
     * Desc:插入课程校区
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/5 8:38 下午
     * @param $data
     * @return mixed
     */
    public static function insertUserCourseAddress($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_address_user_course,$data);
    }

    /**
     * Desc:获取用户的课程选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/6 10:59
     * @param $where
     * @return mixed
     */
    public static function getUserCourseAddress($where)
    {
        return db_get(t_shangjia_address_user_course,$where);
    }


    /**
     * Desc:修改用户课程选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/6 11:22
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editUserCourseAddress($where,$data)
    {
        return db_update(t_shangjia_address_user_course,$data,$where);
    }

    /**
     * Desc:删除同一订单号下的课程地址选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/6 9:24 下午
     * @param $where
     * @return mixed
     */
    public static function deleteUserCourseAddressByWhere($where)
    {
        return db_delete(t_shangjia_address_user_course,$where);
    }

    /**
     * Desc:更新用户课程校区数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 2:26 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateUserCourseAddress($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_address_user_course,$data,$where);
    }

    /**
     * Desc:判断用户是否领取过
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/4 7:23 下午
     * @param $themeid
     * @param $uid
     * @param $shangjiaid
     * @param $coupon_id
     */
    public static function userGetCoupon($themeid,$uid,$workerid)
    {
        global $_P, $_G, $_C,$_S;
        $themeid = $_P['themeid'];
        $theme = Theme::getThemeById($themeid);
        $_C = $config =    Theme::getConfig($themeid);
        $_S = $system = self::getSystem();
        //判断用户是否存在已使用的优惠券
        $used_coupon_flag = self::getUserCoupon($themeid,$uid,false);
        $worker_item = db_get(t_worker,['uid'=>$workerid,'themeid'=>$themeid]);
        //根据workerid查询商家
        $shangjiaid = $worker_item['company'];
        $shangjia_item = db_get(t_shangjia,['id'=>$shangjiaid]);
        $shangjia_name = $theme['jubf'];
        if ($used_coupon_flag){
            //判断是否多价格
            if ($system['bottom_jiage']==0){
                //判断哟优惠券未使用
                if ($used_coupon_flag['status']==1){
                    //判断当前优惠券是否过期
                    $coupon_item= db_get(t_shangjia_coupon,['id'=>$used_coupon_flag['coupon_id']]);
                    //优惠券上架状态
                    if ($coupon_item && $coupon_item['status']==1){
                        if ($coupon_item['shangjiaid']==$shangjiaid){
                            $shangjia_name = $shangjia_item['name'];
                        }
                        $now = date("Y-m-d H:i:s",time());
                        if ($coupon_item && ($coupon_item['use_start_time']<=$now) && ($now<$coupon_item['use_end_time'])){
                            return ['shangjia'=>$shangjia_name,'type'=>1,'price'=>floatval($coupon_item['price'])];
                        }
                    }
                }
            }elseif ($system['bottom_jiage']>0){
                //判断当前用户是否领取了当前商家的优惠券
                $search_user_coupons = db_getall(t_shangjia_user_coupon,['shangjiaid'=>$shangjiaid,'status'=>1,'uid'=>$uid]);
                $tmp_txt_arr = [];
                $now = date("Y-m-d H:i:s",time());
                if ($search_user_coupons){
                    //存在
                    $shangjia_name = $shangjia_item['name'];
                    foreach ($search_user_coupons as $k => $v){
                        $coupon_item = db_get(t_shangjia_coupon,['id'=>$v['coupon_id']]);
                        if ($coupon_item && $coupon_item['status']==1 && ($coupon_item['use_start_time']<=$now) && ($now<$coupon_item['use_end_time'])){
                            $tmp_desc = '';
                            if ($coupon_item['bind_price']==1){
                                $tmp_desc = '￥'.$config['groupprice'].'元可抵用';
                            }elseif ($coupon_item['bind_price']==2){
                                $tmp_desc = '￥'.$config['groupprice2'].'元可抵用';
                            }
                            $tmp_str = ['title'=>floatval($coupon_item['price']).'元券','desc'=>$tmp_desc];
                            array_push($tmp_txt_arr,$tmp_str);
                        }
                    }
                }else{
                    //不存在
                    $search_user_coupons = db_getall(t_shangjia_user_coupon,['shangjiaid'=>0,'status'=>1,'uid'=>$uid]);
                    foreach ($search_user_coupons as $k => $v){
                        $coupon_item = db_get(t_shangjia_coupon,['id'=>$v['coupon_id']]);
                        if ($coupon_item && $coupon_item['status']==1 && ($coupon_item['use_start_time']<=$now) && ($now<$coupon_item['use_end_time'])){
                            $tmp_desc = '';
                            if ($coupon_item['bind_price']==1){
                                $tmp_desc = '￥'.$config['groupprice'].'元可抵用';
                            }elseif ($coupon_item['bind_price']==2){
                                $tmp_desc = '￥'.$config['groupprice2'].'元可抵用';
                            }
                            $tmp_str = ['title'=>floatval($coupon_item['price']).'元券','desc'=>$tmp_desc];
                            array_push($tmp_txt_arr,$tmp_str);
                        }
                    }
                }
                if ($tmp_txt_arr){
                    return ['shangjia'=>$shangjia_name,'type'=>2,'price'=>'','txt_arr'=>$tmp_txt_arr];
                }
            }
            return [];
        }


        if ($worker_item){
            if ($shangjia_item){
                $shangjia_name = $shangjia_item['name'];
                $coupon_price_total = 0;
                $coupon_type = 1;
                $coupon_txt_arr = [];
                //查询商家独用优惠券
                $shangjia_coupon_list = db_getall(t_shangjia_coupon,['themeid'=>$themeid,'shangjiaid'=>$shangjiaid,'status'=>1]);
                if (!$shangjia_coupon_list){
                    //查询商家通用优惠券
                    $shangjia_coupon_list = db_getall(t_shangjia_coupon,['themeid'=>$themeid,'shangjiaid'=>0,'status'=>1]);
                    $shangjia_name = $theme['jubf'];
                }
                if ($shangjia_coupon_list){
                    if (count($shangjia_coupon_list)>1){
                        $coupon_type = 2;
                    }
                    $now = date("Y-m-d H:i:s",time());
                    $insert_value = "";
                    foreach ($shangjia_coupon_list as $k => $v){
                        $tmp_check = db_get(t_shangjia_user_coupon,['themeid'=>$themeid,'uid'=>$uid,'shangjiaid'=>$v['shangjiaid'],'coupon_id'=>$v['id']]);
                        if (!$tmp_check){
                            $item = db_get(t_shangjia_coupon,['id'=>$v['id']]);
                            if ($item && ($item['get_start_time']<=$now) && ($now<=$item['get_end_time'])){
                                $coupon_price_total+= floatval($v['price']);
                                $tmp_str = ['title'=>'','desc'=>''];
                                if ($v['bind_price']==1){
                                    $tmp_str = ['title'=>floatval($v['price']).'元券','desc'=>'￥'.$config['groupprice'].'元可抵用'];
                                }elseif ($v['bind_price']==2){
                                    $tmp_str = ['title'=>floatval($v['price']).'元券','desc'=>'￥'.$config['groupprice2'].'元可抵用'];
                                }
                                array_push($coupon_txt_arr,$tmp_str);
                                $update_coupon_sql = " update ".tablename(t_shangjia_coupon)." set get_num=get_num+1 where id='".$v['id']."' and themeid='".$themeid."'";
                                db_find($update_coupon_sql);
                                $insert_value.= " ('".$themeid."','".$uid."','".$item['shangjiaid']."','".$v['id']."'),";
                            }
                        }
                    }
                    if ($insert_value){
                        $insert_value = rtrim($insert_value,',');
                        $insert_sql = " insert into ".tablename(t_shangjia_user_coupon)." (`themeid`,`uid`,`shangjiaid`,`coupon_id`) values ".$insert_value;
                        db_query($insert_sql);
                        return ['shangjia'=>$shangjia_name,'type'=>$coupon_type,'price'=>$coupon_price_total,'txt_arr'=>$coupon_txt_arr];
                    }
                }
            }
        }
        return [];
    }

    /**
     * Desc:获取用户优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/4 10:24 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserCoupon($themeid,$uid,$is_use = true)
    {
        if (!$is_use){
            return db_get(t_shangjia_user_coupon,['themeid'=>$themeid,'uid'=>$uid,'status'=>1]);
        }
        return db_get(t_shangjia_user_coupon,['themeid'=>$themeid,'uid'=>$uid,'status'=>2]);
    }

    /**
     * Desc:获取用户优惠券记录以及优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/15 3:27 下午
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function getUserCouponInfo($themeid,$uid)
    {
        global $_P;
        $shangjiaid = 0;
        $tmp_sql = " select * from ".tablename(t_userdata_record)." where themeid=$themeid and uid=$uid order by id desc limit 1";
        $fans_userdata_record = db_find($tmp_sql);
        if ($fans_userdata_record['workerid']){
            $worker_item = db_get(t_worker,['uid'=>$fans_userdata_record['workerid'],'themeid'=>$themeid]);
            $shangjiaid = $worker_item['company'];
        }
        $bind_price = 1;
        if (isset($_P['joinid'])){
            if ($_P['joinid']==4){
                $bind_price = 2;
            }elseif ($_P['joinid']==5){
                $bind_price = 3;
            }
        }
        $get_sql = " select a.*,b.bind_price,b.use_start_time,b.use_end_time from ".tablename(t_shangjia_user_coupon)." as a ".
            " left join ".tablename(t_shangjia_coupon)." as b on a.coupon_id=b.id and a.shangjiaid=b.shangjiaid".
            " where a.themeid=$themeid and a.status=1 and a.uid='$uid' and b.bind_price='$bind_price' and a.shangjiaid='$shangjiaid' ";
        $user_coupon_flag = db_find($get_sql);
        if (!$user_coupon_flag){
            $get_sql = " select a.*,b.bind_price,b.use_start_time,b.use_end_time from ".tablename(t_shangjia_user_coupon)." as a ".
                " left join ".tablename(t_shangjia_coupon)." as b on a.coupon_id=b.id ".
                " where a.themeid=$themeid and a.status=1 and a.uid='$uid' and b.bind_price='$bind_price' ";
            $user_coupon_flag = db_find($get_sql);
        }
        if ($user_coupon_flag){
            $now = date("Y-m-d H:i:s",time());
            $coupon_info = db_get(t_shangjia_coupon,['id'=>$user_coupon_flag['coupon_id'],'themeid'=>$themeid]);
            if ($coupon_info && ($coupon_info['use_start_time']<=$now) && ($now<=$coupon_info['use_end_time'])){
                return $coupon_info;
            }else{
                return [];
            }
        }else{
            return [];
        }
    }

    /**
     * Desc:获取查询条件下的商家列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:35 上午
     * @param $where
     * @return mixed
     */
    public  static function getShangjiaList()
    {
        $sql = " select * from ".tablename(t_shangjia)." where id >0 order by displayorder";
        $list = db_select($sql);
        if ($list){
            foreach ($list as $k => $v){
                $workerid = '-'.$v['id'];
                $xuni_order_toal_sql = " select sum(record) as cnt from ".tablename(t_workerreport)." where workerid=$workerid";
                $xuni_order_total = db_find($xuni_order_toal_sql)['cnt'];
                $list[$k]['order_total'] = (int)$v['order_total']+(int)$xuni_order_total;
            }
        }
        return $list;
    }

    /**
     * Desc:获取全部商家以及课程选择数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/9/30 09:29
     * @param $list
     * @param $themeid
     * @return mixed
     */
    public static function getSjCourseTotal($list,$themeid)
    {
        $total = 0;
        if ($list){
            foreach ($list as $k => $val){
                if ($val['id']){
                    $sj_id = $val['id'];
                    $sql = " select count(*) as cnt from ".tablename(t_shangjia_address_user_course)." where themeid=$themeid and shangjiaid=$sj_id";
                    $item_total = db_find($sql)['cnt'];
                    $list[$k]['checked_total'] = $item_total;
                    $total += $item_total;
                }
            }
            $list[0]['checked_total'] = $total;
        }
        return $list;
    }

    /**
     * Desc:通过商家id获取商家信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/19 15:15
     * @param int $id
     * @return mixed
     */
    public static function getShangjiaItem($id=0)
    {
        return db_get(t_shangjia,['id'=>$id]);
    }

    /**
     * Desc:获取两个位置之间的距离/km
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/27 9:13 下午
     * @param string $point1
     * @param string $point2
     * @return float
     */
    public static function distance($point1='',$point2='')
    {
        if (empty($point1) || empty($point2)){
            return 0;
        }
        $point_arr1 = explode(",",$point1);
        $point_arr2 = explode(",",$point2);
        $radLat1=deg2rad((double)$point_arr1[0]);
        $radLat2=deg2rad((double)$point_arr2[0]);
        $radLng1=deg2rad((double)$point_arr1[1]);
        $radLng2=deg2rad((double)$point_arr2[1]);
        $a=$radLat1-$radLat2;//两纬度之差,纬度<90
        $b=$radLng1-$radLng2;//两经度之差纬度<180
        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
        return number_format($s,2);
    }

    /**
     * Desc:获取、搜索课程列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:46 上午
     * @param $themeid
     * @param $shangjiaid
     * @param $name
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public  static function getCourseList($themeid,$shangjiaid,$name,$page_start=0,$page_size=10,$status=0,$sort='',$key=1,$count = false)
    {
        $condition = "";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid = $shangjiaid";
        }
        if ($status){
            $condition .= " and a.status=$status";
        }
        if ($name){
            $condition .= " and a.name like '%".$name."%' or b.name like '%".$name."%' ";
        }
        if ($sort){
            if ($key==1){
                $condition .= " order by  ".$sort." desc";
            }else{
                $condition .= " order by  ".$sort." asc";
            }
        }else{
            $condition .= "  order by b.displayorder,a.show_sort asc ";
        }
        if ($page_size && !$count){
            $condition .= " limit ".$page_start.",".$page_size;
        }
        $sql = "  from ".tablename(t_shangjia_course)." as a".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            "  where a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " select a.*,b.name as shangjia_name,b.address,b.mappoint,b.mobile,b.id as shangjia_id,b.shangjia_rule_id ".$sql;
            return db_select($sql);
        }

    }

    /**
     * Desc:获取价格分组下的商家ids
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2023/3/1 08:37
     * @param int $joinid
     * @return mixed
     */
    public static function getJoinGroupPriceSj($joinid=4)
    {
        $join_key = 'groupprice';
        if ($joinid==4){
            $join_key = 'groupprice2';
        }elseif ($joinid==5){
            $join_key = 'groupprice3';
        }
        $list = [];
        $shangjia_list = db_getall(t_shangjia,['state'=>1]);//获取启用的商家列表
        foreach ($shangjia_list as $k => $v){
            if ($v['join_groupprice']){
                $item_group_price = explode(',',$v['join_groupprice']);
                if (in_array($join_key,$item_group_price)){
                    array_push($list,$v['id']);
                }
            }
        }
        return $list;
    }

    /**
     * Desc:获取商家课程数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/1 5:24 下午
     * @param $themeid
     * @param $shangjiaid
     * @return mixed
     */
    public static function getCourseTotal($themeid,$shangjiaid)
    {
        $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_shangjia_course)." where themeid=$themeid and shangjiaid=$shangjiaid";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取指定的课程详情
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:50 上午
     * @param $themeid
     * @param $id
     * @return mixed
     */
    public  static function getCourseItemById($themeid,$id)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_course)." as a".
        " left join ".tablename(t_shangjia)." as b on a.shangjiaid=b.id ".
        " where a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    /**
     * Desc:通过ids查询课程
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 3:33 下午
     * @param $themeid
     * @param $ids
     * @return mixed
     */
    public static function getCourseListByIds($themeid,$ids)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_course)." as a".
            " left join ".tablename(t_shangjia)." as b on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id in (".$ids.") ";
        return db_select($sql);
    }

    /**
     * Desc:修改课程信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:54 上午
     * @param $where
     * @param $data
     * @return bool
     */
    public  static function editCourseItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_course,$data,$where);
    }

    /**
     * Desc:删除课程
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:56 上午
     * @param $where
     * @return mixed
     */
    public  static function delCourseItem($where)
    {
        return db_delete(t_shangjia_course,$where);
    }

    /**
     * Desc:新增商家课程
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:33 上午
     * @param $data
     * @return mixed
     */
    public  static function insertCourse($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_course,$data);
    }

    /**
     * Desc:新建机构信息记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 6:50 下午
     * @param $data
     * @return mixed
     */
    public static function insertCompanyInfo($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_company_info,$data);
    }

    /**
     * Desc:获取用户机构信息填写
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 6:51 下午
     * @param $where
     * @return mixed
     */
    public static function getCompanyInfoByWhere($where)
    {
        return db_get(t_shangjia_company_info,$where);
    }

    /**
     * Desc:获取商家预留信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/14 1:59 下午
     * @param $themeid
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param string $search
     * @return mixed
     */
    public static function getCompanyInfoList($themeid,$page_start=0,$page_size=10,$start_day='',$end_day='',$search='',$type='',$count = false)
    {
        global $_G;
        $condition=" appid= '".$_G['platform']['appid']."' ";
        if ($search){
            $condition .= " AND mobile LIKE '".$search."'"." or username LIKE '".$search."'"." or company_name LIKE '".$search."'"." or address LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($type){
            $condition .= "  and type=".$type;
        }

        $condition .= " ORDER BY created_at DESC ";


        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = " FROM "
            .tablename(t_shangjia_company_info).
            " WHERE  ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT * ".$sql;
            return db_select($sql);
        }

    }

    /**
     * Desc:获取商户预留合作信息格式化数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/14 2:33 下午
     * @param $themeid
     * @return array[]
     */
    public static function getCompanyTypeCount($themeid)
    {
        global $_G;
        $type_list = [
            ['title'=>'全部','type'=>0],
            ['title'=>'机构','type'=>1],
            ['title'=>'城市服务商','type'=>2]
        ];
        foreach ($type_list as $key =>$val){
            $type = $val['type'];
            if ($type==0){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_company_info)." where  appid= '".$_G['platform']['appid']."'";
            }else{
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_company_info)." where type=$type and appid='".$_G['platform']['appid']."'";
            }
            $type_list[$key]['total'] =  intval(db_find($sql)['cnt']);
        }
        return $type_list;
    }

    /**
     * Desc:获取最近20条订单
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 8:05 下午
     * @param $themeid
     * @return mixed
     */
    public static function getOrderList($themeid)
    {
        $sql = "SELECT username,avatar,mobile,address,type,addtime,fee,addtime FROM ".tablename(t_record)."
                        WHERE themeid =$themeid and status > 0 or status=-2  order by id desc limit 20";
        return db_select($sql);
    }

    //格式化前端展示订单 带虚拟数
    public static function formatFrontOrderList($themeid,$config)
    {
        $fake_order = $config['fakejoin'];
        $groupprice = $config['groupprice'];//拼团
        $primeprice = $config['primeprice'];//单买
        $limit = 80;
        if (strstr($config['softtag0'],"婚纱")!==false ){
            $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+1045;
        }else{
            $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+2545;
        }
        if ($config['touxiang']==0) {
            $xunisql = "SELECT nickname AS username,avatar FROM " . tablename(t_2019fans) .
                " WHERE id >". $kaishishu ." and avatar!=''  LIMIT ".$limit;

        } else {
            $xunisql = "SELECT username,avatar FROM " . tablename(t_2019fans) .
                " WHERE id >". $kaishishu ." and avatar!='' LIMIT ".$limit;

        }
        $virtual = db_select($xunisql);
        $flag = self::getOrderList($themeid);
        if ($flag){
            shuffle($flag);
        }
        if ($fake_order){
            $flag = array_merge($virtual,$flag);
        }
        if ($flag){
            foreach ($flag as $k => $v){
                if (!isset($v['addtime'])){
                    //取昵称中的第一位根据ascii码算得秒数
                    $nickname = mb_substr($v['username'],0,1,'utf-8');
                    $nickname = mb_convert_encoding($nickname, 'GBK');
                    $miao = ord($nickname) % 60;
                    //取昵称中的第一位根据ascii码算得分钟数
                    $nickname = mb_substr($v['username'],1,1,'utf-8');
                    $nickname = mb_convert_encoding($nickname, 'GBK');
                    $fen = ord($nickname) % 60;
                    //取当前时间计算小时数
                    $xiaoshi = date('H')-7;
                    if ($xiaoshi<0){
                        $created_at= date("Y-m-d",strtotime('-1 day'));
                        $xiaoshi = 12;
                        $flag[$k]['fee'] = $groupprice;
                    }else{
                        $created_at=date("Y-m-d");
                        $flag[$k]['fee'] = $primeprice;
                    }

                    if ($xiaoshi==0){
                        $xiaoshi = 1;
                    }
                    $xiaoshi = $xiaoshi==0?7:ord($nickname) % $xiaoshi + 7;
                    if ($xiaoshi<10){ $xiaoshi = "0".$xiaoshi;}
                    if ($fen<10){ $fen = "0".$fen;}
                    if ($miao<10){ $miao = "0".$miao;}
                    $created_at = $created_at ." " .$xiaoshi .":".$fen.":".$miao;
                    $flag[$k]['addtime'] = strtotime($created_at);
                }
            }
        }
        array_multisort(array_column($flag,'addtime'),SORT_DESC,$flag);
        return $flag;
    }

    /**
     * Desc:获取、搜索商家礼品类表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:32 上午
     * @param $themeid
     * @param $shangjiaid
     * @param $name
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public  static function getGiftList($themeid,$shangjiaid=0,$name='',$page_start=0,$page_size=10,$type='',$status=-1,$count = false)
    {
        $condition = "";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid = $shangjiaid";
        }
        if ($status>=0){
            $condition .= " and a.status = $status";
        }
        if (is_numeric($type)){
            $condition .= " and a.type = $type";
        }
        if ($name){
            $condition .= " and a.name like '%".$name."%' or b.name like '%".$name."%' ";
        }
        if ($page_size && !$count){
            $condition .= " limit ".$page_start.",".$page_size;
        }
        $sql = "  from ".tablename(t_shangjia_gift)." as a".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid".$condition;

        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " select a.*,b.name as shangjia_name ".$sql;
            return db_select($sql);
        }
    }

    /**
     * Desc:获取用户礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:12 上午
     * @param $themeid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param int $gift_type
     * @return mixed
     */
    public static function getUserGift($themeid,$shangjiaid=0,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$gift_type=1,$gift_id=0,$status=0,$recordid=0,$count=false,$uid=0)
    {
        $condition="";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($gift_id){
            $condition .= " and a.gift_id=$gift_id ";
        }

        if ($uid){
            $condition .= " and a.uid=$uid ";
        }else{
            if ($recordid){
                $condition .= " and a.order_id=$recordid ";
            }
        }
        if ($status){
            $condition .= " and a.status=$status ";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($gift_type){
            $condition .= " and a.status=$gift_type";
        }
        $condition .= " ORDER BY a.id DESC ";

        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".
            tablename(t_shangjia_user_gift)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia_gift)." AS c ON a.gift_id=c.id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS e ON  e.themeid=$themeid and e.id=a.order_id".
            " LEFT JOIN ".tablename(t_worker)." AS f ON e.workerid=f.uid and f.themeid=$themeid".
            " WHERE a.themeid=$themeid and a.can_use=1 and e.status=1";
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql.$condition));
        }else{
            $res = " SELECT a.id,a.uid,a.gift_id,a.status,a.created_at,a.updated_at,a.shangjiaid,a.workerid,b.avatar,b.nickname,b.username,b.mobile,c.name,c.top_img,c.price,d.name as shangjainame,f.username as workenname ".$sql.$condition;
            return db_select($res);
        }

    }

    /**
     * Desc:获取商家优惠券以及数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/7 9:50 上午
     * @param $themeid
     * @return array[]
     */
    public static function getCouponFromCount($themeid)
    {

        $type_list = [
            ['title'=>'全部','shangjiaid'=>0,'total'=>0]
        ];
        $shangjia = BeilaiModel::getShangjiaList();
        foreach ($shangjia as $key => $val){
            $temp = ['title'=>$val['name'],'total'=>0,'shangjiaid'=>$val['id']];
            array_push($type_list,$temp);
        }
        foreach ($type_list as $key => $val){
            if ($val['title']=='全部'){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_coupon)." where  themeid=".$themeid;
                $type_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }else{
                $shangjia_id = $val['shangjiaid'];
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_coupon)." where shangjiaid=$shangjia_id and  themeid=".$themeid;
                $type_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }
        }
        return $type_list;
    }

    /**
     * Desc:获取用户优惠券 记录 区分类型
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/9/17 17:00
     * @param $themeid
     * @return array[]
     */
    public static function getStatusCouponCount($themeid)
    {
        $status_arr = [
            ['title'=>'全部','status'=>0,'total'=>0],
            ['title'=>'未使用','status'=>1,'total'=>0],
            ['title'=>'已使用','status'=>2,'total'=>0],
        ];
        foreach ($status_arr as $k => $v){
            if (!$v['status']){
                $sql = " select count(*) as cnt from ".tablename(t_shangjia_user_coupon)." where themeid='$themeid'";
            }else{
                $status = $v['status'];
                $sql = " select count(*) as cnt from ".tablename(t_shangjia_user_coupon)." where themeid='$themeid' and status='$status'";
            }
            $status_arr[$k]['total'] = db_find($sql)['cnt'];
        }
        return $status_arr;
    }

    /**
     * Desc:获取礼品类型数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:27 上午
     * @param $themeid
     * @return array[]
     */
    public static function getFlagTypeCount($themeid)
    {
        $type_list = [
            ['title'=>'全部','status'=>0],
            ['title'=>'赠品','status'=>1],
            ['title'=>'礼品','status'=>2]
        ];
        foreach ($type_list as $key =>$val){
            $status = $val['status'];
            if ($status==0){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where  themeid=".$themeid." and can_use=1";
            }else{
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where status=$status and themeid=".$themeid." and can_use=1";
            }
            $type_list[$key]['total'] =  intval(db_find($sql)['cnt']);
        }
        return $type_list;
    }

    /**
     * Desc:获取记录中的用户获取数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:40 上午
     * @param $themeid
     * @return array[]
     */
    public static function getGiftFlagCount($themeid)
    {
        $prize_list = [
            ['title'=>'全部','total'=>0,'gift_id'=>0]
        ];
        $res = self::getGiftList($themeid,0,'',0,0);
//        $sort = array_column($res, 'show_pr');
//        array_multisort($sort, SORT_ASC, $res);
        foreach ($res as $key => $val){
            $temp = ['title'=>$val['name'],'total'=>0,'gift_id'=>$val['id']];
            array_push($prize_list,$temp);
        }
        foreach ($prize_list as $key => $val){
            if ($val['title']=='全部'){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where  themeid=".$themeid." and can_use=1";
                $prize_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }else{
                $gift_id = $val['gift_id'];
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where gift_id=$gift_id and  themeid=".$themeid." and can_use=1";
                $prize_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }
        }
        return $prize_list;
    }

    /**
     * Desc:获取商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:32 上午
     * @param $themeid
     * @param $id
     * @return mixed
     */
    public  static function getGiftItemById($themeid,$id)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_gift)." as a ".
            "left join ".tablename(t_shangjia)." as b on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    /**
     * Desc:修改商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:32 上午
     * @param $where
     * @param $data
     * @return mixed
     */
    public  static function editGiftItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_gift,$data,$where);
    }

    /**
     * Desc:删除商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $where
     * @return mixed
     */
    public  static function delGiftItem($where)
    {
        return db_delete(t_shangjia_gift,$where);
    }

    /**
     * Desc:新增商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $data
     * @return mixed
     */
    public  static function insertGift($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_gift,$data);
    }

    /**
     * Desc:获取、搜索商家优惠券的列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $themeid
     * @param $shangjiaid
     * @param $name
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public  static function getCouponList($themeid,$shangjiaid,$name,$page_start=0,$page_size=10)
    {
        $condition = "";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid = $shangjiaid";
        }
        if ($name){
            $condition .= " and a.name like '%".$name."%' or b.name like '%".$name."%' ";
        }
        if ($page_size){
            $condition .= " limit ".$page_start.",".$page_size;
        }
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_coupon)." as a ".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:获取用户优惠券记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:12 上午
     * @param $themeid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param int $gift_type
     * @return mixed
     */
    public static function getUserCouponFlag($themeid,$shangjiaid=0,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$recordid=0,$count = false,$c_id=0,$status=0)
    {
        $condition="";
        if ($c_id){
            $condition .= " and a.coupon_id=$c_id ";
        }
        if ($status){
            $condition .= " and a.status=$status ";
        }
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($recordid){
            $condition .= " and a.order_id=$recordid ";
        }
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }

        $condition .= " ORDER BY a.created_at DESC ";

        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(t_shangjia_user_coupon)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia_coupon)." AS c ON a.coupon_id=c.id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS e ON a.order_id=e.id and  e.themeid=$themeid".
            " WHERE a.themeid=$themeid ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.status,a.created_at,a.updated_at,a.shangjiaid,b.avatar,b.nickname,b.username,b.mobile,c.name,c.price,d.name as shangjainame ".$sql;
            return db_select($sql);
        }

    }

    public static function getUserCourseFlag($themeid,$shangjiaid=0,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$recordid=0,$sort=1,$c_id= 0,$count = false)
    {
        $condition="";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($c_id){
            $condition .= " and a.course_id=$c_id ";
        }
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($recordid){
            $condition .= " and a.order_id=$recordid ";
        }
        if ($sort==1){
            $condition .= " ORDER BY a.created_at DESC ";
        }else{
            $condition .= " ORDER BY a.updated_at DESC ";
        }

        if ($page_size  && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM "
            .tablename(t_shangjia_address_user_course)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia_course)." AS c ON a.course_id=c.id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS e ON a.order_id=e.id and  e.themeid=$themeid".
            " LEFT JOIN ".tablename(t_worker)." AS f ON e.workerid=f.uid and f.themeid=$themeid".
            " WHERE a.themeid=$themeid and e.status=1 ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.id,a.uid,a.shangjiaid,a.address,a.created_at,a.updated_at,a.status,a.workerid,b.avatar,b.nickname,b.username,b.mobile,c.name,
                c.top_img,d.name as shangjianame,e.fee,e.mobile as order_mobile,f.username as workenname,e.datetime,e.address as raddress,e.formtwo,e.addinfo,e.option  ".$sql;
            return db_select($sql);
        }
    }

    /**
     * Desc:获取指定的优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/16 3:55 下午
     * @param $themeid
     * @param $id
     * @return mixed
     */
    public static function getCoupon($themeid,$id)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_coupon)." as a ".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    /**
     * Desc:获取最早一条记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 3:27 下午
     * @param $themeid
     * @return mixed
     */
    public static function getFirstCoupon($themeid)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_coupon)." as a ".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid order by a.id asc limit 1 ";
        return db_find($sql);
    }
    /**
     * Desc:修改商家优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $where
     * @param $data
     * @return mixed
     */
    public  static function editCouponItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_coupon,$data,$where);
    }

    /**
     * Desc:删除商家优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:30 上午
     * @param $where
     * @return mixed
     */
    public  static function delCouponItem($where)
    {
        return db_delete(t_shangjia_coupon,$where);
    }

    /**
     * Desc:新增商家优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:30 上午
     * @param $data
     * @return mixed
     */
    public  static function insertCoupon($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_coupon,$data);
    }

    /**
     * Desc:获取奖励详情获取指定类型下的奖励列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:29 上午
     * @param $where
     * @param false $is_list
     * @return mixed
     */
    public  static function getRewardByWhere($where,$is_list=false)
    {
        if ($is_list){
            return db_getall(t_shangjia_setting,$where);
        }else{
            return db_get(t_shangjia_setting,$where);
        }
    }

    /**
     * Desc:修改奖励
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:29 上午
     * @param $where
     * @param $data
     * @return mixed
     */
    public  static function editReward($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_setting,$data,$where);
    }

    /**
     * Desc:新增奖励
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:28 上午
     * @return mixed
     */
    public  static function insertReward($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_setting,$data);
    }

    /**
     * Desc:新增商家分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 11:44
     * @param $data
     * @return mixed
     */
    public static function insertCategory($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_category,$data);
    }

    /**
     * Desc:修改商家分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 11:45
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editCategory($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_category,$data,$where);
    }

    /**
     * Desc:获取分类item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 13:38
     * @param $where
     * @return mixed
     */
    public static function getCategory($where)
    {
        return db_get(t_shangjia_category,$where);
    }

    /**
     * Desc:获取查询条件下的分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 14:05
     * @param $where
     * @return mixed
     */
    public static function getCategoryListBy($where)
    {
        return db_getall(t_shangjia_category,$where);
    }

    /**
     * Desc:删除商家分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 11:45
     * @param $where
     * @return mixed
     */
    public static function delCategory($where)
    {
        return db_delete(t_shangjia_category,$where);
    }

    /**
     * Desc:获取查询条件下的分类列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 13:10
     * @param int $themeid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getCategoryList($themeid=1,$search='',$page_start=0,$page_size=10,$count = false)
    {
        $condition = "";
        if ($search){
            $condition .= " and ct_name LIKE'".$search."' ";
        }
        $condition .=" order by ct_sort asc ";
        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  from ".tablename(t_shangjia_category)." where themeid=$themeid ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " select * ".$sql;
            return db_select($sql);
        }

    }

    public static function formatBackendData($themeid)
    {
        $list = self::getCategoryListBy(['themeid'=>$themeid,'pid'=>0]);
        $first = [];
        foreach ($list as $key => $val){
            array_push($first,$val);
            $child = self::getCategoryListBy(['themeid'=>$themeid,'pid'=>$val['ct_id']]);
            if ($child && is_array($child)){
                foreach ($child as $v){
                    $v['ct_name'] = $val['ct_name'].'['.$v['ct_name'].']';
                    array_push($first,$v);
                }
            }
        }
        return $first;
    }
}